import {reqAddToCart,reqCartList,reqCheckCart,reqDeleteCart} from '@/api'
import { getUUID } from '@/util/uuid_token.js'
const state={
    uuid_token:getUUID(),
    cartList:[]
}
const mutations={
    GETCARTLIST(state,cartList){
         state.cartList=cartList
    }
}
const actions={
   async getAddToCart({commit},{skuId,skuNum}){
       let result = await reqAddToCart({skuId,skuNum})
       if(result==200){
           return "ok"
       }else{
           Promise.reject(new Error('faile') )
       }
    },
    async getCartList({commit}){
        let result = await reqCartList()
        if(result.code==200){
          commit("GETCARTLIST",result.data)
        }
    },
    // 即使不用commit，也要写上
    async getCheckCart({commit},{skuId,isChecked}){
        let result =await reqCheckCart({skuId,isChecked})
        console.log(123,result);
        if (result.code==200){
            return 'ok'
        }else{
            Promise.reject(new Error('faile') )
        }
    },
    async getDeleteCart({commit},skuId){
        let result = await reqDeleteCart(skuId)
        if(result.code==200){
            return "ok"
        }else{
            Promise.reject(new Error('falie'))
        }
    },
   deleteCheckedAll({dispatch,getters}){
          let PromiseAll=[]
        getters.cartList.cartInfoList.forEach(element => {
           let promise= element.isChecked==1?dispatch('getDeleteCart',element.skuId):''
           PromiseAll.push(promise)
        });
        return Promise.all(PromiseAll)
    }
}
const getters={
    cartList(state){
        return state.cartList[0]||{}
    }
}
export default{
    state,
    mutations,
    actions,
    getters
}